﻿Imports System.Web
Imports System.Web.Services
Imports System.IO
Imports System.Drawing
Imports SharpCompress.Archive

Public Class ajax
    Implements System.Web.IHttpHandler

    Dim root As String = ""
    Dim dataRoot As String = ""

    Sub ProcessRequest(ByVal context As HttpContext) Implements IHttpHandler.ProcessRequest
        root = context.Server.MapPath("/")
        root = root & "data\"

        Dim resp As String = ""
        Select Case context.Request.Form("cmd")
            Case "browse"
                resp = Execute_Browse(context.Request.Form("br"))
            Case "import"
                Execute_Import(context.Request.Form("path"))

        End Select

        context.Response.Write(resp)
    End Sub

    ReadOnly Property IsReusable() As Boolean Implements IHttpHandler.IsReusable
        Get
            Return False
        End Get
    End Property

    Private Function Execute_Import(_path As String) As Boolean
        Dim archive As IArchive = Nothing
        Select Case Path.GetExtension(_path)
            Case ".cbr"
                archive = Rar.RarArchive.Open(_path)
            Case ".cbx"
                archive = Zip.ZipArchive.Open(_path)
        End Select

        If (archive IsNot Nothing) Then
            Dim importRoot As String = dataRoot & Path.GetFileNameWithoutExtension(_path) & "\"
            If (Directory.Exists(importRoot)) Then
                Directory.CreateDirectory(importRoot)
            End If

            Dim i As Integer = 1
            Dim imgLst As New SortedList(Of String, Image)
            For Each entry As IArchiveEntry In archive.Entries
                Dim ms As New MemoryStream()

                entry.WriteTo(ms)

                Dim img As Image
                img = Image.FromStream(ms)
                img.Save(importRoot & "Page " & i)
                ms.Close()
                ms.Dispose()
                ms = Nothing
                i += 1
            Next

            Return True
        Else
            Return False
        End If

    End Function

    Private Function Execute_Browse(baseRoot As String) As String
        If (baseRoot = "mydocuments") Then
            baseRoot = My.Computer.FileSystem.SpecialDirectories.MyDocuments
        End If
        Dim lstFiles As New clsFiles()
        For Each _file As String In Directory.GetDirectories(baseRoot)
            lstFiles.Add(New clsFile(_file, _file.Replace(baseRoot, "").Replace("\", ""), clsFile.FileType.Directory))
        Next
        For Each _file As String In Directory.GetFiles(baseRoot)
            If (Path.GetExtension(_file) = ".cbr") Then
                lstFiles.Add(New clsFile(_file, Path.GetFileName(_file), clsFile.FileType.File))
            End If
        Next

        Return JsonConverter.ToJSON(lstFiles)
    End Function



End Class